<template>
    <el-card shadow="never" class="border-0">
  
      <!-- 新增|刷新 -->
      <div class="flex items-center justify-between mb-4">
        <el-button type="primary" size="small" @click="handleCreate">新增</el-button>
        <el-tooltip effect="dark" content="刷新数据" placement="top">
          <el-button text @click="initTableData">
            <el-icon :size="20">
              <Refresh />
            </el-icon>
          </el-button>
        </el-tooltip>
      </div>
  
      <!-- 表格数据 -->
      <el-table :data="tableData" stripe style="width: 100%" v-loading="loading">

        <el-table-column label="模板名称" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.templateName }}
          </template>
        </el-table-column>

        <el-table-column label="审批类型" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.approvalType==1?"证书审批":"通用审批" }}
          </template>
        </el-table-column>
  
        <el-table-column label="模板描述" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.description }}
          </template>
        </el-table-column>

        <el-table-column label="状态" align="center">
          <template #default="{ row }">
            {{ row.state==1?"在用":"下架" }}
          </template>
        </el-table-column>

        <!-- <el-table-column label="创建人" align="center">
          <template #default="{ row }">
            {{ row.createUserId }}
          </template>
        </el-table-column> -->

        <el-table-column label="创建时间" align="center">
          <template #default="{ row }">
            {{ dateFormatter(row.createTime) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="250" align="center">
          <template #default="scope">
            <small v-if="scope.row.super == 1" class="text-sm text-gray-500">暂无操作</small>
            <div v-else>
                <!-- <el-button v-if="scope.row.state==0" type="primary" size="small" text @click="handleEdit(scope.row)">修改</el-button> -->
                <!-- <el-button v-else type="primary" size="small" text disabled @click="handleEdit(scope.row)">修改</el-button> -->

                <el-popconfirm v-if="scope.row.state==0" title="是否要上架该模板？" confirmButtonText="确认" cancelButtonText="取消"
                    @confirm="changeState(scope.row.templateId,1)">
                    <template #reference>
                        <el-button type="primary" size="small" text>上架</el-button>
                    </template>
                </el-popconfirm>
                <el-popconfirm  v-if="scope.row.state==1" title="是否要下架该模板？" confirmButtonText="确认" cancelButtonText="取消"
                    @confirm="changeState(scope.row.templateId,0)">
                    <template #reference>
                        <el-button type="primary" size="small" text>下架</el-button>
                    </template>
                </el-popconfirm>
                <el-button type="primary" size="small" text @click="showNodes(scope.row)">详情</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 新增|修改弹窗 -->
      <FormDrawer ref="formDrawerRef" :title="drawerTitle" @submit="handleSubmit">
  
        <el-form :model="form" ref="formRef" :rules="rules" label-width="80px" :inline="false">
          
          <el-form-item label="模板名称" prop="templateName">
            <el-input v-model="form.templateName" placeholder="模板名称"></el-input>
          </el-form-item>

          <el-form-item label="模板描述" prop="description">
            <el-input type="textarea" :rows="4" v-model="form.description" placeholder="模板描述"></el-input>
          </el-form-item>
        </el-form>
      
      </FormDrawer>

      <!-- 审批节点操作弹窗 -->
      <FormDrawer size="70%" 
        ref="approvalNodeListDrawerRef" 
        title="模板详情" 
        showSubBtn="0" 
        @isClosed="isClosed" 
        @submit="handleSubmit">

        <el-form label-width="80px" :inline="false">
          <el-form-item label="操作:" prop="templateName">
            <el-button v-if="isEdit == true" type="primary" size="small" @click="handleEdit()">修改</el-button>
            <el-button v-else type="primary" size="small" disabled>修改</el-button>

            <el-popconfirm title="是否要删除该审核模板？" confirmButtonText="确认" cancelButtonText="取消"
                @confirm="clickDeleteBtn()">
                <template #reference>
                    <el-button v-if="isEdit == true" type="primary" size="small">删除</el-button>
                    <el-button v-else type="primary" size="small" disabled>删除</el-button>
                </template>
            </el-popconfirm>
          </el-form-item>
          <el-form-item label="模板名称:" prop="templateName">
            <span>{{ rowDataNow.templateName }}</span>
          </el-form-item>
          <el-form-item label="模板描述:" prop="description">
            <span>{{ rowDataNow.description }}</span>
          </el-form-item>
        </el-form>

        <SelectApprovalNode v-if="showApprovalNodeTable" :templateId="templateId" :isEdit="isEdit"></SelectApprovalNode>
      </FormDrawer>
    </el-card>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue"
import FormDrawer from "~/components/FormDrawer.vue"
import {toast} from "~/composables/util"
import { dateFormatter } from '~/utils/common.js'
import { getTemplateById,getApprovalTemplateList,addApprovalTemplate,updateApprovalTemplate,deleteApprovalTemplate,approvalTemplateChangeState } from "~/api/approvalApi"
import SelectApprovalNode from "~/components/select-approval-node.vue";


//模版节点相关参数
const templateId = ref(null)
const approvalNodeListDrawerRef = ref(null)
const showApprovalNodeTable = ref(false)
const isEdit = ref(true)


// 表格数据
const tableData = ref([])
const loading = ref(false)


// 生命周期函数
onMounted(() => {
  //初始化列表数据
  initTableData()
})

// 获取数据
function initTableData() {

  loading.value = true
  getApprovalTemplateList()
    .then(res => {
        if(res){
          tableData.value = res      
        }else{
          tableData.value = []  
        }
    })
    .finally(() => {
      loading.value = false
    })
}

// 表单部分
const formDrawerRef = ref(null)
const formRef = ref(null)
const form = reactive({
  templateName: "",
  description: ""
})
//执行表单校验
const rules = {
    templateName: [
    { required: true, message: '模板名称不能为空', trigger: 'change' }
  ],
  description: [
    { required: true, message: '模板描述不能为空', trigger: 'change' }
  ]
}

//是否是编辑弹窗
const editId = ref(0)
const drawerTitle = computed(() => editId.value ? "修改" : "新增")
//当前行值
const rowDataNow = ref({
    templateName: "",
    description: ""
})


//提交表单
const handleSubmit = () => {
    //console.log("form:",JSON.stringify(form))
    //表单校验
    formRef.value.validate((valid) => {
        if (!valid) return
        //loading
        formDrawerRef.value.showLoading()
        //根据是否是修改标记，判断执行新增接口还是修改接口
        const fun = editId.value ? updateApprovalTemplate(editId.value, form) : addApprovalTemplate(form)
        fun.then(res => {
            toast(drawerTitle.value + "成功")
            //当前行值回显
            rowDataNow.value.templateName = form.templateName
            rowDataNow.value.description = form.description

            // 修改刷新当前页，新增刷新第一页
            initTableData(editId.value ? false : 1)
            formDrawerRef.value.close()
        })
        .finally(() => {
            //close loading
            formDrawerRef.value.hideLoading()
        })
    })
}

// 重置表单
function resetForm(row = false) {
  if (formRef.value) formRef.value.resetFields()
  if (row) {
    for (const key in form) {
      form[key] = row[key]
    }
  }
}

// 新增按钮点击事件
const handleCreate = () => {
  //修改标记置为0
  editId.value = 0
  resetForm({
    templateName: "",
    description: ""
  })
  //打开弹窗
  formDrawerRef.value.open()
}

// 上架|下架
const changeState = (templateId,state) => {
  approvalTemplateChangeState(templateId,state).then(res => {
        if(state==1){
            toast("上架成功")
        }else{
            toast("下架成功")
        }
        initTableData()
    })
    .finally(() => {
    })
}

// 编辑
const handleEdit = () => {
  formDrawerRef.value.open()
}

// 删除
const clickDeleteBtn = () => {
  loading.value = true
  let paramIo = {templateId:editId.value}
  deleteApprovalTemplate(paramIo).then(res => {
      toast("删除成功")
      //关闭右侧弹窗
      approvalNodeListDrawerRef.value.close()
      initTableData()
  })
  .finally(() => {
      loading.value = false
  })
}

//节点操作
const showNodes = (row) => {

  //相当与编辑-------
  editId.value = row.templateId
  resetForm(row)
  rowDataNow.value.templateName = row.templateName
  rowDataNow.value.description = row.description
  //相当与编辑-------

  //是否可编辑，下架的状态才可编辑
  if(row.state==0){
    isEdit.value = true
  }else{
    isEdit.value = false
  }
  templateId.value = row.templateId
  approvalNodeListDrawerRef.value.open()
  showApprovalNodeTable.value = true
}

//弹窗关闭通知父组件
function isClosed() {
  showApprovalNodeTable.value = false
}

</script>